<!-- src/components/ai-assistant/index.vue -->
<template>
  <div class="ai-assistant">
    <div class="ai-header">
      <h3>AI 助手</h3>
      <a-button type="text" @click="clearHistory">
        <template #icon>
          <icon-delete />
        </template>
      </a-button>
    </div>
    
    <div class="ai-chat-history" ref="chatHistoryRef">
      <div 
        v-for="(message, index) in chatHistory" 
        :key="index" 
        :class="['message', message.role]"
      >
        <div class="message-avatar">
          <icon-user v-if="message.role === 'user'" />
          <icon robot v-else />
        </div>
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div v-if="message.loading" class="loading">
            <a-spin size="small" />
            <span>AI正在思考中...</span>
          </div>
        </div>
      </div>
    </div>
    
    <div class="ai-input-area">
      <a-textarea
        v-model="inputMessage"
        placeholder="请输入你想询问AI的问题..."
        :auto-size="{ minRows: 2, maxRows: 4 }"
        @press-enter="sendMessage"
        :disabled="isLoading"
      />
      <a-button 
        type="primary" 
        @click="sendMessage" 
        :loading="isLoading"
        :disabled="!inputMessage.trim() || isLoading"
      >
        发送
      </a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue';
import type { Ref } from 'vue';

// 定义消息类型
interface Message {
  role: 'user' | 'assistant';
  content: string;
  loading?: boolean;
}

// 响应式数据
const inputMessage = ref('');
const isLoading = ref(false);
const chatHistory: Ref<Message[]> = ref([]);
const chatHistoryRef = ref<HTMLElement | null>(null);

// 发送消息到AI
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;
  
  const userMessage = inputMessage.value.trim();
  
  // 添加用户消息到聊天历史
  chatHistory.value.push({
    role: 'user',
    content: userMessage
  });
  
  // 清空输入框
  const currentMessage = inputMessage.value;
  inputMessage.value = '';
  
  // 添加AI回复占位符
  const aiMessageIndex = chatHistory.value.length;
  chatHistory.value.push({
    role: 'assistant',
    content: '',
    loading: true
  });
  
  // 滚动到底部
  scrollToBottom();
  
  try {
    isLoading.value = true;
    
    // TODO: 这里你需要替换为实际的API调用
    const response = await callLocalAI(currentMessage);
    
    // 更新AI回复
    chatHistory.value[aiMessageIndex].content = response;
    chatHistory.value[aiMessageIndex].loading = false;
    
  } catch (error) {
    console.error('AI请求失败:', error);
    chatHistory.value[aiMessageIndex].content = '抱歉，AI助手暂时无法回答您的问题，请稍后再试。';
    chatHistory.value[aiMessageIndex].loading = false;
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

// 调用本地AI API的函数（你需要根据实际情况修改）
const callLocalAI = async (message: string): Promise<string> => {
  // 这里是你需要实现的API调用逻辑
  // 示例：
  /*
  const response = await fetch('http://localhost:你的端口/ai/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: message,
      // 其他你需要的参数
    }),
  });
  
  if (!response.ok) {
    throw new Error('网络请求失败');
  }
  
  const data = await response.json();
  // 假设返回的数据结构中有 result 字段
  return data.result || data.response || 'AI没有返回有效内容';
  */
  
  // 临时模拟返回，你需要替换为实际的API调用
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`这是AI对"${message}"的回复。请在callLocalAI函数中实现真实的API调用逻辑。`);
    }, 1000);
  });
};

// 清空聊天历史
const clearHistory = () => {
  chatHistory.value = [];
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatHistoryRef.value) {
      chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight;
    }
  });
};
</script>

<style scoped lang="less">
.ai-assistant {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid var(--color-neutral-3);
  border-radius: 4px;
  background-color: var(--color-bg-2);
}

.ai-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--color-neutral-3);
  
  h3 {
    margin: 0;
    font-size: 16px;
  }
}

.ai-chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  gap: 12px;
  
  &.user {
    align-self: flex-end;
  }
  
  &.assistant {
    align-self: flex-start;
  }
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: rgb(var(--primary-6));
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.message-text {
  padding: 8px 12px;
  border-radius: 4px;
  max-width: 300px;
  word-wrap: break-word;
  
  .user & {
    background-color: rgb(var(--primary-6));
    color: white;
  }
  
  .assistant & {
    background-color: var(--color-fill-2);
  }
}

.loading {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: var(--color-text-3);
}

.ai-input-area {
  padding: 16px;
  border-top: 1px solid var(--color-neutral-3);
  display: flex;
  flex-direction: column;
  gap: 12px;
  
  :deep(.arco-textarea-wrapper) {
    margin-bottom: 8px;
  }
}
</style>